<?php

namespace addons\good\controllers;
use addons\good\models\CategoryModel;
use controllers\AdminApi;

class category extends AdminApi {

    /**
     * 初始化
     */
    public function onStepUp(){
        $this->model = new CategoryModel();
    }

    /**
     * 分类接口
     * @param string $title
     * @return array
     */
    public function index($title = '') {
        $map = [];
        if ($title){
            $map['title like'] = $title;
        }
        $list = $this->model->where($map)->select();
        foreach ($list as $key => &$val){
            $val['image'] = get_image($val['image']);
        }
        return self::returnJson($list);
    }

    /**
     * 更新前操作
     * @param array $data
     * @return bool
     */
    protected function onUpdateBefore(&$data = []){
        if (self::$post['id']) {
            $find = $this->model->getFind(self::$post['id']);
            if (!$find) {
                $this->error = '分类不存在';
                return false;
            }
        }
        $find = $this->model->where(['title' => self::$post['title']])->field('id,image')->find();
        if ($find && $find['id'] != self::$post['id']) {
            $this->error = '此分类已存在';
            return false;
        }
        if (self::$post['image']) {
            if (!self::$post['image'] = $this->uploadImg(self::$post['image'], $find['image'] ? $find['image'] : '')) {
                $this->error = '图片保存失败';
                return false;
            }
        }
        return true;
    }

	/**
	 * 设置弹窗标题
	 * @return string
	 * @author Colin <amcolin@126.com>
	 * @date 2021-12-30 下午4:05
	 */
	protected static function setPageTitle() {
		return '分类';
	}

	/**
	 * 设置面包屑
	 * @return array
	 * @author Colin <amcolin@126.com>
	 * @date 2021-12-30 下午4:05
	 */
	protected static function setCrumbs() {
		return ['商品管理' , '分类列表'];
	}

    /**
     * 删除后
     * @param bool $status
     * @param array $find
     * @return bool
     */
    protected function onDeleteAfter($status, $find = []){
        if ($find['image']){
            unlink(ltrim($find['image'] , '/'));
        }
        return true;
    }
}
